import { useState, useMemo, useEffect } from 'react';
import './Template.css';
import TemplateTabs from '../../components/TemplateTabs';
import SearchBar from '../../components/SearchBar';
import VirtualWaterfall from '../../components/VirtualWaterfall';

// 模板数据类型定义
interface TemplateData {
  id: number;
  name: string;
  image: string;
  colorScheme: {
    bg: string;
    text: string;
    color: string;
  };
  style: string;
  layout: string;
  downloads: number;
  likes: number;
  isNew: boolean;
  isPremium: boolean;
}

function Index() {
  const [activeTab, setActiveTab] = useState('图片模板');
  const [selectedChannel, setSelectedChannel] = useState('全部');
  const [selectedMaterial, setSelectedMaterial] = useState('全部');
  const [selectedIndustry, setSelectedIndustry] = useState('全部');
  const [materialExpanded, setMaterialExpanded] = useState(true);
  const [industryExpanded, setIndustryExpanded] = useState(true);
  const [selectedSort, setSelectedSort] = useState('综合排序');
  const [showSetsOnly, setShowSetsOnly] = useState(false);
  const [selectedColor, setSelectedColor] = useState('全部');
  const [selectedStyle, setSelectedStyle] = useState('全部');
  const [selectedLayout, setSelectedLayout] = useState('全部');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [columns, setColumns] = useState(4);

  const channels = ['全部', '电商', '微信/公众号', '社群发圈', '生活娱乐', '小红书', '短视频平台', '线下印刷', '线下电商'];
  const materials = ['全部', '海报', '公众号首图', '文章长图', '小红书配图', '小红书封面', '全屏海报', '电商竖版海报', '商品主图', '公众号次图', '电商横版海报', '电商方形图', '电商详情图', '电商轮播图'];
  const industries = ['全部', '通用', '教育培训', '金融保险', '商品零售', '企业行政', '美容美妆', '食品生鲜', '服饰箱包', '政务媒体', '生活服务', '餐饮美食', '汽车房产', '医疗健康', '科技数码', '家居建材', '运动户外'];
  const sortOptions = ['综合排序', '最新上传', '最多下载'];
  const colors = ['颜色', '红色', '蓝色', '绿色', '黄色', '紫色', '橙色', '粉色'];
  const styles = ['风格', '简约', '商务', '可爱', '复古', '科技', '自然', '艺术'];
  const layouts = ['版式', '横版', '竖版', '方形', '长图', '海报'];

  // 响应式列数计算
  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth;
      if (width < 768) {
        setColumns(2);
      } else if (width < 1024) {
        setColumns(3);
      } else if (width < 1440) {
        setColumns(4);
      } else {
        setColumns(5);
      }
    };

    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 生成随机模板数据
  const generateTemplates = (): TemplateData[] => {
    const templateNames = [
      '稿定科技 简介', '荔枝主题设计', '手机聊天模板', '数据图表模板', 
      '明星主题设计', '通用设计模板', '电商海报设计', '公众号封面图',
      '小红书配图', '企业宣传册', '产品展示图', '活动海报',
      '节日祝福卡', '简历模板', '名片设计', '菜单设计',
      '房产广告', '汽车宣传', '美食推广', '服装展示',
      '化妆品海报', '教育培训', '金融理财', '医疗健康',
      '婚礼请柬', '生日贺卡', '新年祝福', '圣诞主题',
      '情人节海报', '母亲节祝福', '父亲节感恩', '教师节致敬',
      '国庆节庆祝', '春节团圆', '中秋佳节', '端午安康'
    ];
    const mockImages = [
      'https://picsum.photos/300/400?random=1',
      'https://picsum.photos/300/500?random=2',
      'https://picsum.photos/300/350?random=3',
      'https://picsum.photos/300/450?random=4',
      'https://picsum.photos/300/380?random=5',
      'https://picsum.photos/300/420?random=6',
      'https://picsum.photos/300/360?random=7',
      'https://picsum.photos/300/480?random=8',
      'https://picsum.photos/300/400?random=9',
      'https://picsum.photos/300/440?random=10',
      'https://picsum.photos/300/370?random=11',
      'https://picsum.photos/300/460?random=12',
      'https://picsum.photos/300/390?random=13',
      'https://picsum.photos/300/430?random=14',
      'https://picsum.photos/300/410?random=15',
      'https://picsum.photos/300/470?random=16',
      'https://picsum.photos/300/400?random=17',
      'https://picsum.photos/300/450?random=18',
      'https://picsum.photos/300/380?random=19',
      'https://picsum.photos/300/420?random=20',
      'https://picsum.photos/300/360?random=21',
      'https://picsum.photos/300/480?random=22',
      'https://picsum.photos/300/440?random=23',
      'https://picsum.photos/300/400?random=24',
      'https://picsum.photos/300/460?random=25',
      'https://picsum.photos/300/420?random=26',
      'https://picsum.photos/300/380?random=27',
      'https://picsum.photos/300/450?random=28',
      'https://picsum.photos/300/410?random=29',
      'https://picsum.photos/300/470?random=30',
      'https://picsum.photos/300/430?random=31',
      'https://picsum.photos/300/390?random=32',
      'https://picsum.photos/300/460?random=33',
      'https://picsum.photos/300/440?random=34',
      'https://picsum.photos/300/400?random=35',
      'https://picsum.photos/300/480?random=36'
    ];
    const colorSchemes = [
      { bg: 'linear-gradient(135deg, #667eea, #764ba2)', text: 'white', color: '紫色' },
      { bg: 'linear-gradient(135deg, #f093fb, #f5576c)', text: 'white', color: '粉色' },
      { bg: 'linear-gradient(135deg, #4ecdc4, #44a08d)', text: 'white', color: '绿色' },
      { bg: 'linear-gradient(135deg, #ff6b6b, #ffa500)', text: 'white', color: '红色' },
      { bg: 'linear-gradient(135deg, #a8edea, #fed6e3)', text: '#333', color: '蓝色' },
      { bg: 'linear-gradient(135deg, #ffecd2, #fcb69f)', text: '#333', color: '橙色' },
      { bg: 'linear-gradient(135deg, #a8caba, #5d4e75)', text: 'white', color: '绿色' },
      { bg: 'linear-gradient(135deg, #ff9a9e, #fecfef)', text: '#333', color: '粉色' },
      { bg: 'linear-gradient(135deg, #fad0c4, #ffd1ff)', text: '#333', color: '橙色' },
      { bg: 'linear-gradient(135deg, #ffecd2, #fcb69f)', text: '#333', color: '黄色' }
    ];
    const styleTypes = ['简约', '商务', '可爱', '复古', '科技', '自然', '艺术'];
    const layoutTypes = ['横版', '竖版', '方形', '长图', '海报'];
    return Array.from({ length: 100 }, (_, index) => ({
      id: index + 1,
      name: templateNames[index % templateNames.length],
      image: mockImages[index % mockImages.length],
      colorScheme: colorSchemes[Math.floor(Math.random() * colorSchemes.length)],
      style: styleTypes[Math.floor(Math.random() * styleTypes.length)],
      layout: layoutTypes[Math.floor(Math.random() * layoutTypes.length)],
      downloads: Math.floor(Math.random() * 10000) + 100,
      likes: Math.floor(Math.random() * 500) + 10,
      isNew: Math.random() > 0.8,
      isPremium: Math.random() > 0.7
    }));
  };

  const allTemplates = generateTemplates();

  // 根据筛选条件过滤模板
  const filteredTemplates = useMemo(() => {
    return allTemplates.filter(template => {
      if (searchKeyword.trim() && !template.name.toLowerCase().includes(searchKeyword.toLowerCase())) {
        return false;
      }
      if (selectedColor !== '全部' && template.colorScheme.color !== selectedColor) {
        return false;
      }
      if (selectedStyle !== '全部' && template.style !== selectedStyle) {
        return false;
      }
      if (selectedLayout !== '全部' && template.layout !== selectedLayout) {
        return false;
      }
      return true;
    });
  }, [allTemplates, searchKeyword, selectedColor, selectedStyle, selectedLayout]);

  const getDisplayMaterials = () => {
    if (materialExpanded) {
      return materials;
    }
    return materials.slice(0, 5);
  };
  const getDisplayIndustries = () => {
    if (industryExpanded) {
      return industries;
    }
    return industries.slice(0, 5);
  };

  // 渲染单个模板卡片
  const renderTemplateCard = (template: TemplateData) => (
    <div 
      key={template.id} 
      className="template-card"
      style={{ height: 320 }}
    >
      <div className="card-image">
        <img src={template.image} alt={template.name} />
        {template.isNew && <div className="new-badge">NEW</div>}
        {template.isPremium && <div className="premium-badge">PRO</div>}
        <div className="card-overlay">
          <div className="overlay-stats">
            <span className="stat-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="currentColor"/>
              </svg>
              {template.likes}
            </span>
            <span className="stat-item">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z" fill="currentColor"/>
              </svg>
              {template.downloads}
            </span>
          </div>
        </div>
      </div>
      <div className="card-title">
        {template.name}
        <div className="card-tags">
          <span className="tag">{template.colorScheme.color}</span>
          <span className="tag">{template.style}</span>
          <span className="tag">{template.layout}</span>
        </div>
      </div>
    </div>
  );

  return (
    <div className="template-page">
      {/* 搜索框 */}
      <div className="template-search-section">
        <SearchBar 
          onSearch={(keyword) => setSearchKeyword(keyword)}
          onInputChange={(value) => setSearchKeyword(value)}
        />
      </div>
      {/* 使用封装的TemplateTabs组件 */}
      <TemplateTabs 
        activeTab={activeTab} 
        onTabChange={setActiveTab} 
      />
      {/* 筛选区域 */}
      <div className="filter-section">
        {/* 渠道筛选 */}
        <div className="filter-row">
          <span className="filter-label">渠道</span>
          <div className="filter-options">
            {channels.map(channel => (
              <button
                key={channel}
                className={`filter-option ${selectedChannel === channel ? 'selected' : ''}`}
                onClick={() => setSelectedChannel(channel)}
              >
                {channel}
              </button>
            ))}
          </div>
        </div>
        {/* 物料筛选 */}
        <div className="filter-row">
          <span className="filter-label">物料</span>
          <div className="filter-options">
            {getDisplayMaterials().map(material => (
              <button
                key={material}
                className={`filter-option ${selectedMaterial === material ? 'selected' : ''}`}
                onClick={() => setSelectedMaterial(material)}
              >
                {material}
              </button>
            ))}
            <button 
              className="filter-option more-option"
              onClick={() => setMaterialExpanded(!materialExpanded)}
            >
              {materialExpanded ? '收起' : '更多'}
              <span className={`arrow-down ${materialExpanded ? 'expanded' : ''}`}>
                {materialExpanded ? '▲' : '▼'}
              </span>
            </button>
          </div>
        </div>
        {/* 行业筛选 */}
        <div className="filter-row">
          <span className="filter-label">行业</span>
          <div className="filter-options">
            {getDisplayIndustries().map(industry => (
              <button
                key={industry}
                className={`filter-option ${selectedIndustry === industry ? 'selected' : ''}`}
                onClick={() => setSelectedIndustry(industry)}
              >
                {industry}
              </button>
            ))}
            <button 
              className="filter-option more-option"
              onClick={() => setIndustryExpanded(!industryExpanded)}
            >
              {industryExpanded ? '收起' : '更多'}
              <span className={`arrow-down ${industryExpanded ? 'expanded' : ''}`}>
                {industryExpanded ? '▲' : '▼'}
              </span>
            </button>
          </div>
        </div>
      </div>
      {/* 排序和筛选选项 */}
      <div className="sort-section">
        <div className="sort-options">
          {sortOptions.map(option => (
            <button
              key={option}
              className={`sort-option ${selectedSort === option ? 'selected' : ''}`}
              onClick={() => setSelectedSort(option)}
            >
              {option}
              {option === '最新上传' && <span className="new-tag">New</span>}
            </button>
          ))}
        </div>
        <div className="filter-controls">
          <select 
            className="filter-select"
            value={selectedColor}
            onChange={(e) => setSelectedColor(e.target.value)}
          >
            {colors.map(color => (
              <option key={color} value={color}>{color}</option>
            ))}
          </select>
          <select 
            className="filter-select"
            value={selectedStyle}
            onChange={(e) => setSelectedStyle(e.target.value)}
          >
            {styles.map(style => (
              <option key={style} value={style}>{style}</option>
            ))}
          </select>
          <select 
            className="filter-select"
            value={selectedLayout}
            onChange={(e) => setSelectedLayout(e.target.value)}
          >
            {layouts.map(layout => (
              <option key={layout} value={layout}>{layout}</option>
            ))}
          </select>
          <label className="toggle-label">
            <input 
              type="checkbox" 
              checked={showSetsOnly}
              onChange={(e) => setShowSetsOnly(e.target.checked)}
            />
            只看套装
          </label>
        </div>
      </div>
      {/* 模板内容预览 - 使用虚拟滚动 */}
      <div className="template-content">
        {filteredTemplates.length > 0 ? (
          <VirtualWaterfall
            items={filteredTemplates}
            renderItem={renderTemplateCard}
            itemWidth={200}
            gap={20}
            containerHeight={600}
            overscan={10}
            columns={columns}
          />
        ) : (
          <div className="no-results">
            <p>没有找到符合条件的模板</p>
            <button onClick={() => {
              setSelectedColor('全部');
              setSelectedStyle('全部');
              setSelectedLayout('全部');
            }}>
              清除筛选条件
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

export default Index;
